#!/usr/bin/env python

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users

import os
import datetime
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

#from google.appengine.dist import use_library
#use_library('django', '1.2')

from google.appengine.ext.webapp import template

from engine.util import *
from engine.Person import *
from engine.Answer import *
#from engine.questions import *
from engine.questions2 import *

from questionCode import *
from calendarCode import *
from mobileCom import *

class ShowSignUp(webapp.RequestHandler):
    def get(self):
        template_values = {
        }

        path = os.path.join(os.path.dirname(__file__), 'signup.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        person = Person()
        # TODO: Check if email is taken
        # Save new user
        person.firstName = self.request.get('firstName').strip()
        person.name = self.request.get('name').strip()
        person.lastName = self.request.get('lastName').strip()
        person.email = self.request.get('email').strip()
        person.password = self.request.get('password1').strip()
        person.save()
        # log in
        self.response.headers.add_header('Set-Cookie', 'userId=%s; expires=Fri, 31-Dec-2020 23:59:59 GMT' % person.id)
        self.response.out.write("User created: " + person.firstName)
        self.response.out.write("<br>" + str(person.id))
        self.redirect("/")

class ShowLogin(webapp.RequestHandler):
    def get(self):
        userId = self.request.cookies.get('userId', '')
        if userId and userId != "None":
            person = LoadPersonFromId(userId)
            if person:
                self.redirect("/?logout=1")
                
        template_values = {
        }

        path = os.path.join(os.path.dirname(__file__), 'login.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        email = self.request.get('email').strip()
        person = LoadPerson(email)
        if not person:
            self.response.out.write("Unknown user: " + email)
            self.response.out.write("<br><a href='/'>Try again</a> or <a href='/signup'>sign up</a>.")
            return
        if person.password != self.request.get('password').strip():
            self.response.out.write("Wrong password for user: " + email)
            return
        self.response.headers.add_header('Set-Cookie', 'userId=%s; expires=Fri, 31-Dec-2020 23:59:59 GMT' % person.id)
        self.response.out.write("Id set to " + str(person.id))
        self.redirect("/")

class ShowIndex(webapp.RequestHandler):
    def get(self):
        if self.request.get('logout'):
            self.response.headers.add_header('Set-Cookie', 'userId=None; expires=Fri, 31-Dec-2020 23:59:59 GMT')
            self.response.out.write("Logged out")
            self.redirect("/login")
            return
        else:
            userId = self.request.cookies.get('userId', '')
            #print userId, not userId, userId == "None"
            if not userId or userId == "None" or userId == None:
                self.redirect("/login")
                return

        person = LoadPersonFromId(userId)
        if not person:
            self.redirect("/login")
            return

#        location = LoadLocation(205)
#        #location.save()
#        person.homeLocation = location
#        #location = Location(lat = 51.1, lng = 5.3)
#        location = LoadLocation(206)
#        #location.save()
#        person.workLocation = location
#        #person.lastQuestionsDate = datetime.datetime.now()
        date = TimeNow()
        person.setLocation(date)
        person.setActivity(date)

        mapcode = ""
        mapcode = GetMapCode(person.currentLocation, None)

        calendarCode = GetCalendarCode(person, date)
        questionCode = ""
        questionCode = GetQuestionCode(person)

        if person.lastQuestionsDate == None:
            textToUser = """
        Hej %s, <p> Jeg er din zentienz. Jeg bev&aelig;ger mig rundt i verden og tilstr&aelig;ber at v&aelig;re de samme steder som dig. 
        <p>
        Lige nu ved jeg meget lidt om dig, s&aring; jeg g&aelig;tter p&aring; at du befinder dig p&aring; R&aring;dhuspladsen
        i K&oslash;benhavn.
        <br>
        Du kan hj&aelig;pe mig videre ved at besvare sp&oslash;rgsm&aring;l ude til h&oslash;re.
        <p>
        mvh, din zentienz
        """ % (person.firstName)
        else:
            textToUser = "Klokken er %s. Jeg %s." % (PrintTime(TimeNow()), person.currentActivity.name)

            #textToUser = textToUser + "<p> %s" % Distance(person.homeLocation, person.workLocation)
        #cl = person.currentLocation
        #textToUser = textToUser + "<p>%f, %f" % (cl.lat, cl.lng)
        
        template_values = {
            'person': person,
            'mapcode': mapcode,
            'calendarCode': calendarCode,
            'questionCode': questionCode,
            'textToUser': textToUser
        }

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class ShowMobileMap(webapp.RequestHandler):
    def get(self):
        userId = self.request.get('userId', '')
        if not userId or userId == "None" or userId == None:
            self.response.out.write("Error: no user")
            return

        # check is (lat, lng) from GPS was provided
        gpsLocation = None
        cLat = self.request.get('cLat', '')
        cLng = self.request.get('cLng', '')
        if not cLat or cLat == "None" or not cLng or cLng == "None":
            pass
        else:
            gpsLocation = Location()
            gpsLocation.lat = cLat
            gpsLocation.lng = cLng
 
        person = LoadPersonFromId(userId)
        if not person:
            self.response.out.write("Error: person not found")
            return

        date = TimeNow()
        person.setLocation(date)
        person.setActivity(date)

        mapcode = ""
        mapcode = GetMapCode(person.currentLocation, gpsLocation)
       
        template_values = {
            'person': person,
            'mapcode': mapcode,
        }

        path = os.path.join(os.path.dirname(__file__), 'mapMobile.html')
        self.response.out.write(template.render(path, template_values))

class ProcessAnswers(webapp.RequestHandler):
    def post(self):
        userId = int(self.request.cookies.get('userId', ''))
        #print userId
        person = LoadPersonFromId(userId)
        if not person:
            self.response.out.write("ERROR. User not found:" + str(userId))
            return
        person.lastQuestionsDate = TimeNow()
        person.save()
        qId1 = self.request.get('id1').strip()
        qId2 = self.request.get('id2').strip()
        qId3 = self.request.get('id3').strip()
        a1 = self.request.get('a1').strip()
        a2 = self.request.get('a2').strip()
        a3 = self.request.get('a3').strip()
        aux1 = self.request.get('aux1').strip()
        aux2 = self.request.get('aux2').strip()
        aux3 = self.request.get('aux3').strip()
        #print "1", qId1, a1, aux1
        #print "2", qId2, a2, aux2
        #print "3", qId3, a3, aux3
        if qId1:
            processAnswer(qId1, person, a1, aux1)
        if qId2:
            processAnswer(qId2, person, a2, aux2)
        if qId3:
            processAnswer(qId3, person, a3, aux3)
        #self.response.out.write(a1 + " " + a2 + " " + a3)
        self.redirect("/")
        
class ShowAbout(webapp.RequestHandler):
    def get(self):
        template_values = {
        }

        path = os.path.join(os.path.dirname(__file__), 'about.html')
        self.response.out.write(template.render(path, template_values))

class ShowGetAddress(webapp.RequestHandler):
    def get(self):

        template_values = {
        }

        path = os.path.join(os.path.dirname(__file__), 'getAddress.html')
        self.response.out.write(template.render(path, template_values))
    
    def post(self):
        location = Location()
        location.zipCode = int(self.request.get('zip').strip())
        location.street = self.request.get('street').strip()
        lat = self.request.get('lat').strip()
        if lat:
            location.lat = float(lat)
            location.lng = float(self.request.get('lng').strip())

        if self.request.get('confirmed').strip():
            SetLocationCoordinates(location)        
            userId = int(self.request.cookies.get('userId', ''))
            person = LoadPersonFromId(userId)
            if not person:
                self.response.out.write("ERROR. User not found:" + str(userId))
                return
            location.save()
            person.homeLocation = location
            person.save()
            self.redirect("/")

        if location.lat:
            mapCode = GetMapCode(location, None)
        else:
            mapCode = ""

        confirm = 1
        
        template_values = {
            'confirm': confirm,
            'mapCode': mapCode,
            'location': location
        }

        path = os.path.join(os.path.dirname(__file__), 'getAddress.html')
        self.response.out.write(template.render(path, template_values))

class ShowAddCalEntry(webapp.RequestHandler):
    def get(self):

        template_values = {
        }

        path = os.path.join(os.path.dirname(__file__), 'addCalEntry.html')
        self.response.out.write(template.render(path, template_values))

class DeleteAllData(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write("Delete Location\n")
        self.response.out.write(DeleteTable("Location"))
        self.response.out.write("Delete Person\n")
        self.response.out.write(DeleteTable("Person"))
        self.response.out.write("Delete CalendarEntry\n")
        self.response.out.write(DeleteTable("CalendarEntry"))
        self.response.out.write("Delete Activity\n")
        self.response.out.write(DeleteTable("Activity"))

class QA:
    def __init__(self, q, a):
        self.q = q
        self.a = a

class ShowAnswers(webapp.RequestHandler):
    def get(self):
        userId = self.request.cookies.get('userId', '')
        if not userId or userId == "": 
            self.redirect("/")
            
        person = LoadPersonFromId(userId)
        if not person:
            self.response.out.write("ERROR. User not found:" + str(userId))
            return

        answers = loadAnswersFromUserId(userId)
        questions = ReadAllQuestionsDic()

        qas = []
        for a in answers:
            qa = QA(questions[a.questionId], a)
            qas.append(qa)
            
        template_values = {
            'person': person,
            'qas': qas
        }

        path = os.path.join(os.path.dirname(__file__), 'answers.html')
        self.response.out.write(template.render(path, template_values))

def main():
    application = webapp.WSGIApplication([('/', ShowIndex),
                                         ('/mMap', ShowMobileMap),
                                         ('/mCom', MobileCom),
                                         ('/login', ShowLogin),
                                         ('/answers', ProcessAnswers),
                                         ('/address', ShowGetAddress),
                                         ('/about', ShowAbout),
                                         ('/addCalEntry', ShowAddCalEntry),
                                         ('/deleteAllData', DeleteAllData),
                                         ('/showAnswers', ShowAnswers),
                                         ('/signup', ShowSignUp)],
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
